<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="style.css" />
  <title>My Blog</title>
</head>

<body>

  <div id="posts-container">
    
  </div>

  <div class="loader" style="display: none;">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
  </div>
  <script src="./axios.js"></script>
  <script>
    let page = 1;
    let isLoading = false;
    let url = 'https://jsonplaceholder.typicode.com/posts';
    let boxNode = document.querySelector('#posts-container');
    let loaderNode = document.querySelector('.loader');

    // 获取数据
    async function getData() {
      let data = {
        _limit: 5,
        _page: page
      };
      let res = await axios.get(url, { params: data });
      console.log(res.data);
      return res.data;
    }

    // 渲染数据
    async function render() {
      if (isLoading) return;
      isLoading = true;
      loaderNode.classList.add('show')

      try {
        let data = await getData();
        let newPosts = data.map(item => `
          <div class="post">
            <div class="number">${item.id}</div>
            <div class="post-info">
              <h2 class="post-title">${item.title}</h2>
              <p class="post-body">${item.body}</p>
            </div>
          </div>
        `).join('');
        boxNode.innerHTML += newPosts;
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        isLoading = false;
        loaderNode.classList.remove('show')
      }
    }

    render();

    // 上拉加载更多，滚动到滚动条距离页面底部 50px 时，加载下一页数据
    window.addEventListener('scroll', () => {
      const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

      if (clientHeight + scrollTop >= scrollHeight - 50 && !isLoading) {
        page++;
        // render();
      }
    });
  </script>
</body>

</html>